/*
 * @Author: szx
 * @Date: 2022-02-25 14:47:49
 * @LastEditTime: 2022-02-25 15:10:45
 * @Description:
 * @FilePath: \leetcode\1-99\15\15_2.js
 */
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
    if (nums.length < 3) return [];
    nums.sort((a, b) => a - b);
    const n = nums.length;
    const res = [];
    for (let i = 0; i < n; i++) {
        if (nums[i] > 0) return res;
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        let left = i + 1;
        let right = n - 1;
        while (right > left) {
            const num = nums[i] + nums[left] + nums[right];
            if (num == 0) {
                res.push([nums[i], nums[left], nums[right]]);
                while (left < right && nums[left] === nums[left + 1]) left++;
                while (left < right && nums[right] === nums[right - 1]) right--;
                left++;
                right--;
            } else if (num > 0) right--;
            else left++;
        }
    }
    return res;
};
